package com.xxwy.idle;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.buffer.UnpooledHeapByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;


/**
 * @author wy
 * @date 2020/3/6 10:13
 */
public class ServerHandler extends ChannelInboundHandlerAdapter {

  /**
   * 表示建立连接，一旦建立连接，第一个被执行
   * @param ctx
   * @throws Exception
   */
  @Override
  public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    Channel channel = ctx.channel();
    //推送 xxx来到聊天室
  }

  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    Channel channel = ctx.channel();
    System.out.println("客户端 ：" + channel.remoteAddress() +"上线");
  }

  /**
   * 便是channel处于不活跃状态
   * @param ctx
   * @throws Exception
   */
  @Override
  public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    Channel channel = ctx.channel();
    System.out.println("客户端 ：" + channel.remoteAddress() +"离线");
  }

  @Override
  public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {

    Channel channel = ctx.channel();
    //推送 xxx离开聊天室
    //channelGroup.remove(channel); 自动删除
    System.out.println("handlerRemoved " + channel.remoteAddress());
  }


  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel channel = ctx.channel();
    System.out.println("客户端 ：" + channel.remoteAddress() +msg);
    System.out.println(msg);
    ByteBuf hello_client = Unpooled.copiedBuffer("hello client", CharsetUtil.UTF_8);
    ctx.writeAndFlush(hello_client);
  }
}
